﻿using System;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Animation;
using Bookvar.ObjectModel;
using Bookvar.UI;

namespace Bookvar.Console
{
    public class DynamicTopic
    {
        private TopicContentPresenter presenter;
        private readonly DynamicTopicCollection subtopics;
        private readonly Topic topic;

        internal Topic Topic
        {
            get { return topic; }
        }

        public DynamicTopicCollection Subtopics
        {
            get { return subtopics; }
        }

        internal DynamicTopic( TopicContentPresenter presenter )
        {
            this.presenter = presenter;
            topic = presenter.Topic;
            subtopics = new DynamicTopicCollection( presenter );
        }

        public DynamicTopic()
        {
            topic = new Topic();
        }

        public string Name
        {
            get { return topic.Name; }
            set { topic.Name = value; }
        }

        public void MoveTo( int x, int y )
        {
            EnsurePresenter();

            presenter.X = x;
            presenter.Y = y;
            presenter.IsMoved = true;
        }

        public void Dance()
        {
            EnsurePresenter();

            presenter.RenderTransformOrigin = new Point( 0.5, 0.5 );
            presenter.RenderTransform = new SkewTransform();
            Storyboard dance = (Storyboard) presenter.FindResource( "dance" );
            presenter.BeginStoryboard( dance );
        }

        private void EnsurePresenter()
        {
            if ( presenter == null )
            {
                DynamicTopic mainTopic = ConsoleControl.MainTopic;
                if (mainTopic != null)
                {
                    TopicContentPresenter newPresenter = mainTopic.presenter.Owner.FindTopicContentPresenter(topic.ID);
                    if (newPresenter != null)
                    {
                        presenter = newPresenter;
                    }
                }
                else
                {
                    throw new InvalidOperationException("First add the topic to the mind map");
                }
            }
        }
    }
}